<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
    <crudOperation :permission="permission">
    </crudOperation>
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px" v-formkey="{query:toQuery}">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据类型">
                <el-select v-model="orderType" collapse-tags multiple class="edit-input" placeholder="请选择单据状态" style="width: 100%;">
                  <el-option
                    v-for="(item,index) in dict.t_business_history_order_type"
                    :key="index"
                    multiple
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="往来单位">
                <!--                <zSelect multiple :value.sync="customerIds"  url="/api/dropDown/basCustomerList" style="width:  100%;"/>-->
                <table-select
                  :tableColumns="[{prop:'code',label:'单位编码',width:'100'},{prop:'name',label:'往来单位名称',width: '280'}]"
                  :value.sync="query.customerIds"
                  placeholder="请选择往来单位"
                  url="/api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="query.orderRemark" placeholder="输入备注进行搜索"/>
              </el-form-item>
            </el-col>
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--              <rrOperation :crud="crud"/>-->
<!--            </el-col>-->
          </el-row>
          <el-row class="flex fow-reverse">
            <el-button class="filter-item"  size="mini" type="primary" @click="crud.toQuery()">搜索</el-button>
            <el-button class="filter-item" plain   size="mini" type="primary"
                       @click="resetQuery">重置</el-button>
          </el-row>
        </el-form>
      </div>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="id">
            <el-input v-model="form.id" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="业务日期">
            <el-input v-model="form.busDate" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="单据id">
            <el-input v-model="form.orderId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="单据编码">
            <el-input v-model="form.orderCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="往来单位id">
            <el-input v-model="form.customerId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="往来单位编码">
            <el-input v-model="form.customerCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="往来单位名称">
            <el-input v-model="form.customerName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="仓库id">
            <el-input v-model="form.warehouseId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="仓库编码">
            <el-input v-model="form.warehouseCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-input v-model="form.warehouseName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="条数">
            <el-input v-model="form.count" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="箱数">
            <el-input v-model="form.boxCount" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="form.goodsCount" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="含税金额">
            <el-input v-model="form.taxAmount" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="单据状态(SAVE:保存 PASS:审核 CLOSE:关闭)">
            <el-input v-model="form.orderStatus" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="是否验收(0:否 1:是)">
            <el-input v-model="form.isAccept" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="单据备注">
            <el-input v-model="form.orderRemark" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="添加人id">
            <el-input v-model="form.createUserId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="添加人编码">
            <el-input v-model="form.createUserCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="添加人名称">
            <el-input v-model="form.createUserName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="添加时间">
            <el-input v-model="form.createTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="审核人id">
            <el-input v-model="form.auditUserId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="审核人编码">
            <el-input v-model="form.auditUserCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="审核人名称">
            <el-input v-model="form.auditUserName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="审核时间">
            <el-input v-model="form.auditTime" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <!--表格渲染-->
      <!--表格渲染-->
      <el-table ref="table" stripe border
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                v-if="isShowTable"
                show-summary
                :height="tableHeight"
                :row-class-name="toBeRed"
                :summary-method="sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                @row-dblclick="row=>setQuery(row.orderId,row.orderType)"
                @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
              <span v-if="item.type == 1" style="margin-left: 10px" >{{ scope.row[`${item.prop}`] }}</span>
              <span v-else-if="item.type == 2" style="margin-left: 10px"  >{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-else-if="item.type == 3" style="margin-left: 10px"  >{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
              <span v-else-if="item.type == 4" style="margin-left: 10px">
<!--                  <span v-if="item.prop === 'orderCode'" style="color: blue;cursor: pointer" @click="jumpBuyOrder(scope.row.orderId,scope.row.orderType)">-->
                    {{scope.row[`${item.prop}`]}}
<!--                  </span>-->
              </span>
            </template>
        </el-table-column>
<!--        <el-table-column v-if="columns.visible('id')" prop="id" label="id" />-->
<!--        <el-table-column v-if="columns.visible('busDate')" prop="busDate" label="业务日期">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.busDate) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('orderId')" prop="orderId" label="单据id" />&ndash;&gt;-->
<!--        <el-table-column v-if="columns.visible('orderCode')" prop="orderCode" label="单据编码" />-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('customerId')" prop="customerId" label="往来单位id" />&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('customerCode')" prop="customerCode" label="往来单位编码" />&ndash;&gt;-->
<!--        <el-table-column v-if="columns.visible('customerName')" prop="customerName" label="往来单位名称" />-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('warehouseId')" prop="warehouseId" label="仓库id" />&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('warehouseCode')" prop="warehouseCode" label="仓库编码" />&ndash;&gt;-->
<!--        <el-table-column v-if="columns.visible('warehouseName')" prop="warehouseName" label="仓库名称" />-->
<!--        <el-table-column v-if="columns.visible('count')" prop="count" label="条数" />-->
<!--        <el-table-column v-if="columns.visible('boxCount')" prop="boxCount" label="箱数" />-->
<!--        <el-table-column v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" />-->
<!--        <el-table-column v-if="columns.visible('taxAmount')" prop="taxAmount" label="含税金额" />-->
<!--        <el-table-column v-if="columns.visible('orderStatus')" prop="orderStatus" label="单据状态" />-->
<!--        <el-table-column v-if="columns.visible('isAccept')" prop="isAccept" label="是否验收" />-->
<!--        <el-table-column v-if="columns.visible('orderRemark')" prop="orderRemark" label="单据备注" />-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('createUserId')" prop="createUserId" label="添加人id" />&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('createUserCode')" prop="createUserCode" label="添加人编码" />&ndash;&gt;-->
<!--        <el-table-column v-if="columns.visible('createUserName')" prop="createUserName" label="添加人名称" />-->
<!--        <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="添加时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('auditUserId')" prop="auditUserId" label="审核人id" />&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column v-if="columns.visible('auditUserCode')" prop="auditUserCode" label="审核人编码" />&ndash;&gt;-->
<!--        <el-table-column v-if="columns.visible('auditUserName')" prop="auditUserName" label="审核人名称" />-->
<!--        <el-table-column v-if="columns.visible('auditTime')" prop="auditTime" label="审核时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.auditTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column v-permission="['admin','reportBusinessHistory:edit','reportBusinessHistory:del']" label="操作" width="150px" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <udOperation-->
<!--              :data="scope.row"-->
<!--              :permission="permission"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudReportBusinessHistory from '@/api/erp/reportBusinessHistory'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { publicListKey } from "@/utils/key";
import {salesDetailKey} from "@/utils/key";
import {get} from '@/api/erp/reportBusinessHistory'
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import {getDict} from "@/api/erp/tableColumnConfig";

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '经营历程',
  url: 'api/reportBusinessHistory',
  sort: 'busDate,desc',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false,
  },
  crudMethod: {...crudReportBusinessHistory}
})
const defaultForm = {
  id: null,
  busDate: null,
  orderId: null,
  orderCode: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  count: null,
  boxCount: null,
  goodsCount: null,
  taxAmount: null,
  orderStatus: null,
  isAccept: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null
}
export default {
  name: 'reportBusinessHistory',
  components: { pagination, crudOperation, rrOperation, udOperation, jTableColumnConfig },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), publicListKey, salesDetailKey, tablemixins],
  dicts: ['t_business_history_order_type'],
  data() {
    return {
      permission: {
        add: ['admin', 'reportBusinessHistory:add'],
        edit: ['admin', 'reportBusinessHistory:edit'],
        del: ['admin', 'reportBusinessHistory:del'],
        import: ['admin', 'reportBusinessHistory:import'],
        export: ['admin', 'reportBusinessHistory:export'],
        copy: ['admin', 'reportBusinessHistory:copy'],
        upload: ['admin', 'reportBusinessHistory:upload'],
        download: ['admin', 'reportBusinessHistory:download'],
        pass: ['admin', 'reportBusinessHistory:pass'],
        reject: ['admin', 'reportBusinessHistory:reject'],
        closed: ['admin', 'reportBusinessHistory:closed'],
        invalid: ['admin', 'reportBusinessHistory:invalid'],
        stop: ['admin', 'reportBusinessHistory:stop'],
        recover: ['admin', 'reportBusinessHistory:recover'],
      },
      rules: {
      },
      billType:{},
      indexlist: [],
      orderType:[],
      customerIds:[],
      red:['11','9','4','2','7','6'],
      redIndexList: [],
      scroll:"",
      tableHeight: 0
    }
  },
  activated() {
    console.log("!!!!!!")
    console.log(sessionStorage.getItem('businessBodyScrollTop'),sessionStorage.getItem('businessTableScrollTop'))
    window.scrollTo(0,sessionStorage.getItem('businessBodyScrollTop') || 0)
    this.$refs.table.bodyWrapper.scrollTo(0,sessionStorage.getItem('businessTableScrollTop') || 0)
  },
  deactivated() {
    sessionStorage.setItem('businessBodyScrollTop',document.documentElement.scrollTop)
    sessionStorage.setItem('businessTableScrollTop',this.$refs.table.bodyWrapper.scrollTop)
  },
  watch: {
    orderType:{
      handler(n){
        if (n) {
          this.$set(this.query, 'orderType', this.orderType.join(','))
        }else {
          this.$set(this.query, 'orderType', null)
        }
      },
      deep:true
    },

  },
  mounted() {
    let _this = this
    window.onresize = () => {
      return (() => {
        _this.setTableHeight()
      })();
    };
  },
  created() {
    this.setTableHeight()
    const data = {
      dictCode: 't_business_history_order_type',
      size: 999
    }
    getDict(data).then(res => {
      res.content.forEach(item => {
        item.label.includes('期初') && this.indexlist.push(item.value)
        this.billType[item.value] = item.remark
      })
    })
  },
  methods: {
    setTableHeight(){
      const ratio =this.getRatio() / 100
      this.tableHeight = (window.screen.height - (200*ratio)) / ratio
    },
    getRatio() {
      var ratio = 0;
      var screen = window.screen;
      var ua = navigator.userAgent.toLowerCase();

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }

      } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
      }

      if (ratio) {
        ratio = Math.round(ratio * 100);
      }
      return ratio;
    },

    setQuery(id,orderType){
      this.$router.push(this.billType[orderType]+`${this.indexlist.includes(orderType)?'?id=':'/'}`+id)


    },
    toBeRed({row}){
      return this.red.includes(row.orderType)?'red':'';
    },
    sumRow({ columns, data }){
      console.log(this.crud)
      const sums = []
      for (let i in  columns) {
        if (['boxCount', 'count', 'goodsCount','taxAmount'].includes(columns[i].property)) {
          let selectSum = 0
          this.$refs.table.selection.forEach(item => {
            console.log( item[columns[i].property])
            selectSum += item[columns[i].property]
          })
          sums[i] = <p>{selectSum}
            <hr/>
            {this.crud.summary[columns[i].property] || 0}</p>
        }
        sums[0] = <p>选中
          <hr/>
          合计</p>
      }
      return sums
    },
    resetQuery(){
      this.orderType  = []
      this.crud.resetQuery()
      this.$forceUpdate()
    },
    jumpBuyOrder(id,orderType){
      console.log(this.billType[orderType]+`${this.indexlist.includes(orderType)?'?id=':'/'}`+id)
      this.$router.push(this.billType[orderType]+`${this.indexlist.includes(orderType)?'?id=':'/'}`+id)
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },

  }
}
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
